# coding=utf-8
from math import log
import operator
import treePlotter


def createDataSet():
    dataSet = [[1, 1, 'yes'],
               [1, 1, 'yes'],
               [1, 0, 'no'],
               [0, 1, 'no'],
               [0, 1, 'no']]
    labels = ['no surfacing', 'flippers']
    # change to discrete values
    return dataSet, labels


# 求出熵的值
def calcShannonEnt(dataSet):
    # 数据行数
    numEntries = len(dataSet)
    labelCounts = {}
    # 求出各个标签出现的次数
    for featVec in dataSet:  # the the number of unique elements and their occurance
        currentLabel = featVec[-1]
        if currentLabel not in labelCounts.keys():
            labelCounts[currentLabel] = 0
        labelCounts[currentLabel] += 1
    # 初始化熵值
    shannonEnt = 0.0
    # 对于每个标签求信息期望值并求和
    for key in labelCounts:
        prob = float(labelCounts[key]) / numEntries
        shannonEnt -= prob * log(prob, 2)  # log base 2
    return shannonEnt


# 按照给定的特征值划分数据集，
# dataSet为源数据集，
# axis为划分数据集的特征(第几列，一列为一个特征)
# value为需要返回的特征值
def splitDataSet(dataSet, axis, value):
    retDataSet = []
    for featVec in dataSet:
        if featVec[axis] == value:
            # reducedFeatVec是把当前特征列去除之后，这一行数据的其他值
            reducedFeatVec = featVec[:axis]
            reducedFeatVec.extend(featVec[axis + 1:])
            retDataSet.append(reducedFeatVec)
    return retDataSet


# Entropy是熵的意思
# 选择一个最好的特征值为当前的分支
def chooseBestFeatureToSplit(dataSet):
    # 特征值个数
    numFeatures = len(dataSet[0]) - 1  # the last column is used for the labels
    # 基础的熵
    baseEntropy = calcShannonEnt(dataSet)
    # 选择的最好特征值获得的熵增益
    bestInfoGain = 0.0
    # 初始化最好的特征值下标
    bestFeature = -1
    # 遍历特征值
    for i in range(numFeatures):
        # 把当前特征值的所有结值 单独列一列出来
        featList = [example[i] for example in dataSet]
        # 当前特征值有多少种情况
        uniqueVals = set(featList)
        newEntropy = 0.0
        # 按当前特征值来分类，来计算出一个新的熵值
        for value in uniqueVals:
            subDataSet = splitDataSet(dataSet, i, value)
            prob = len(subDataSet) / float(len(dataSet))
            newEntropy += prob * calcShannonEnt(subDataSet)
        # 计算熵增益
        infoGain = baseEntropy - newEntropy
        # 求出最大熵增益的列
        if (infoGain > bestInfoGain):  # compare this to the best gain so far
            bestInfoGain = infoGain  # if better than current best, set to best
            bestFeature = i
    return bestFeature  # returns an integer


#  返回最大分类的标签
def majorityCnt(classList):
    classCount = {}
    for vote in classList:
        if vote not in classCount.keys():
            classCount[vote] = 0
        classCount[vote] += 1
    sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]


# 创建决策树
def createTree(dataSet, labels):
    # classList 所有分类
    classList = [example[-1] for example in dataSet]
    # 如果只有一个分类，则退出递归
    if classList.count(classList[0]) == len(classList):
        return classList[0]
    # 如果已经没有特征值，只有分类值了，退出递归
    if len(dataSet[0]) == 1:
        return majorityCnt(classList)
    # 求出当前所有特征值中最好的特征值，并求出其label
    bestFeat = chooseBestFeatureToSplit(dataSet)
    bestFeatLabel = labels[bestFeat]
    # 将该当前最好的label作为key
    myTree = {bestFeatLabel: {}}
    # 在label数据集中将该label删除
    del (labels[bestFeat])

    featValues = [example[bestFeat] for example in dataSet]
    uniqueVals = set(featValues)
    for value in uniqueVals:
        # 复制当前labels copy all of labels, so trees don't mess up existing labels
        subLabels = labels[:]
        myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value), subLabels)
    return myTree


def classify(inputTree, featLabels, testVec):
    firstStr = inputTree.keys()[0]
    secondDict = inputTree[firstStr]
    featIndex = featLabels.index(firstStr)
    key = testVec[featIndex]
    valueOfFeat = secondDict[key]
    if isinstance(valueOfFeat, dict):
        classLabel = classify(valueOfFeat, featLabels, testVec)
    else:
        classLabel = valueOfFeat
    return classLabel


def storeTree(inputTree, filename):
    import pickle
    fw = open(filename, 'w')
    pickle.dump(inputTree, fw)
    fw.close()


def grabTree(filename):
    import pickle
    fr = open(filename)
    return pickle.load(fr)


def main():
    myData, Lables = createDataSet()
    # myTree = createTree(myData, Lables)
    # storeTree(myTree, "classifierStorage.txt")
    myTree = grabTree("classifierStorage.txt")
    print classify(myTree, Lables, [1, 1])


def createLensesTree():
    fr = open('ID3/lenses.txt')
    fr2 = open('ID3/lensesLabels.txt')
    lenses = [line.strip().split('\t') for line in fr.readlines()]
    lensesLabels = fr2.readline().strip().split(' ')
    myTree = createTree(lenses, lensesLabels)
    storeTree(myTree, 'ID3/lensesTree.txt')
    treePlotter.createPlot(myTree)


if __name__ == '__main__':
    createLensesTree()
